package com.itstudio.myforumsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itstudio.myforumsystem.common.Result;
import com.itstudio.myforumsystem.entity.Article;
import com.itstudio.myforumsystem.entity.Type;
import com.itstudio.myforumsystem.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@ResponseBody
@RequestMapping("/type")
@Slf4j
//文章管理模块
public class TypeController {
    @Autowired
    private TypeService typeService;


    @PostMapping
    public Result save(@RequestBody Type type){
        typeService.saveOrUpdate(type);
        return Result.success();
    }


    //查询所有信息
    @GetMapping
    public Result findAll(){
        List<Type> list = typeService.list();
        for (Type type:list){

            //通过type的id拿到三个文章
              List<Article> limitNumArticle  =typeService.FindLimitNumArticle(type.getId());

              type.setChildren(limitNumArticle);
        }
        return Result.success(list);
    }

    //查找文章通过名字
    @GetMapping("/findAllByTypeName/{name}")
    public Result findAllByTypeName(@PathVariable String name){
        typeService.FindAllInfor(name);
        return Result.success();
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        typeService.removeById(id);
        return Result.success();
    }
    //分页查询
    @GetMapping("/page")
    public IPage<Type> findPage(@RequestParam(required = false) Integer pageNum,
                                @RequestParam(required = false) Integer pageSize,
                                @RequestParam(required = false,defaultValue = "") String name//避免搜索为空时的报错
    ){
        // 检查 pageNum 是否为 null，如果是则设置默认值为 1
        pageNum = (pageNum != null) ? pageNum : 1;
        // 检查 pageSize 是否为 null，如果是则设置默认值为 10（或者你想设置的其他默认值）
        pageSize = (pageSize != null) ? pageSize : 10;
       IPage<Type> page = new Page<>(pageNum,pageSize);
       QueryWrapper<Type> queryWrapper = new QueryWrapper<>();
        if (!"".equals(name)&&name!=null){
            queryWrapper.like("name",name);
        }
       return typeService.page(page,queryWrapper);

    }

    //批量删除
    @PostMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids){
        return typeService.removeByIds(ids);
    }

}
